<?php

namespace app\admin\controller;

use app\api\controller\Myshopify;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * shopify导入订单管理
 *
 * @icon fa fa-circle-o
 */
class Feditionordershopify extends Backend
{
    
    /**
     * Feditionordershopify模型对象
     * @var \app\admin\model\Feditionordershopify
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Feditionordershopify;
        $this->view->assign("statusList", $this->model->getStatusList());

        $accounturl = $this->request->param('accounturl');
        $this->assignconfig('accounturl', $accounturl);
        $daystamp = $this->request->param('daystamp');
        $this->assignconfig('daystamp', $daystamp);
        $gateway = $this->request->param('gateway');
        $this->assignconfig('gateway', $gateway);
        $type = $this->request->param('type');
        $this->assignconfig('type', $type);
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $where2 = array();
            $accounturl = $this->request->param('accounturl');
            if(!empty($accounturl)){
                $where2['accounturl'] = $accounturl;
            }
            $where3 = array();
            $created_at = $this->request->param('daystamp');
            if(!empty($created_at)){
                $startdate = strtotime(date('Y-m-d 00:00:00', $created_at));
                $enddate = strtotime(date('Y-m-d 23:59:59', $created_at));
                $where3['created_at'] = array(array('egt',$startdate),array('elt',$enddate));
            }
            $where4 = array();
            $gateway = $this->request->param('gateway');
            if(!empty($gateway)){
                $where4['gateway'] = $gateway;
            }
            $where5 = array();
            $type = $this->request->param('type');
            if($type == 1){
                $where5['financial_status'] = array('in','paid,partially_refunded');
            }
            if($type == 2){
                $where5['financial_status'] = 'refunded';
            }

            $list = $this->model
                ->where($where)
                ->where($where2)
                ->where($where3)
                ->where($where4)
                ->where($where5)
                ->order($sort, $order)
                ->paginate($limit);
            $lists = $list->items();
            if($lists){
                foreach ($lists as $k=>$v){
                    $accounturl = Db::name('fedition_accounturl')->where('id', '=', $v['accounturl'])->find();
                    if($accounturl){
                        $lists[$k]['accounturl_name'] = $accounturl['name'];
                    }else{
                        $lists[$k]['accounturl_name'] = '店铺名称已删除';
                    }
                    // 商品名称
                    $fedition_orderquantitys = Db::name('fedition_orderquantity')->where('order_id',$v['id'])->order('price desc')->select();
                    $quantitys = 0;
                    $fedition_orderquantitys2 = array();
                    if(!empty($fedition_orderquantitys)){
                        foreach ($fedition_orderquantitys as $kf=>$vf) {
                            if($vf['title'] == 'Tip'){
                                
                            }else{
                                $fedition_orderquantitys2[] = $vf;
                                if(!empty($vf['sku'])){
                                    $skunew = substr($vf['sku'],-1);
                                    if(strpos(substr($vf['sku'],-2),'-') !== false){ 
                                        // 包含
                                        if((int)$skunew > 0 && (int)$skunew <= 200){
                                            $quantitys += $vf['quantity'] * (int)$skunew;
                                        }else{
                                            $quantitys = $quantitys + $vf['quantity'];
                                        }
                                    }else{
                                        $quantitys = $quantitys + $vf['quantity'];
                                    }
                                }else{
                                    $quantitys = $quantitys + $vf['quantity'];
                                }
                            }
                        }
                    }
                    if(!empty($fedition_orderquantitys2)){
                        $fedition_orderquantity = $fedition_orderquantitys2[0];
                    }else{
                        $fedition_orderquantity = array();
                    }
                    $lists[$k]['orderquantity_quantitys'] = $quantitys;
                    // $fedition_orderquantity = Db::name('fedition_orderquantity')->where('order_id',$v['id'])->order('price desc')->find();
                    if (!empty($fedition_orderquantity)) {
                        $lists[$k]['orderquantity_title'] = $fedition_orderquantity['title'];
                        //sku
                        if(!empty($fedition_orderquantity['sku'])){
                            $lists[$k]['orderquantity_sku'] = $fedition_orderquantity['sku'];
                        }else{
                            $variants = Db::name('products_shopify_variants')->where('variants_id',$fedition_orderquantity['variant_id'])->find();
                            if(empty($variants['sku'])){
                                $variants2 = Db::name('products_shopify_variants')->where('product_id',$fedition_orderquantity['product_id'])->select();
                                if(!empty($variants2['sku'])){
                                    foreach ($variants2 as $k2=>$v2) {
                                        if(!empty($v2['sku'])){
                                            $variants = $v2;
                                            break;
                                        }
                                    }
                                }
                            }
                            if(!empty($variants['sku'])){
                                $lists[$k]['orderquantity_sku'] = $variants['sku'];
                            }   
                        }
                    }else{
                        $lists[$k]['orderquantity_title'] = '';
                        $lists[$k]['orderquantity_sku'] = '';
                    }
                    //运单号
//                    $orderfulfillments = Db::name('fedition_orderfulfillments')->where('order_id',$v['id'])->find();
//                    if (!empty($orderfulfillments)) {
//                        $lists[$k]['tracking_company'] = $orderfulfillments['tracking_company'];
//                        $lists[$k]['tracking_number'] = $orderfulfillments['tracking_number'];
//                    } else {
//                        $lists[$k]['tracking_company'] = '';
//                        $lists[$k]['tracking_number'] = '';
//                    }
                }
            }
            $Statistics = array();
            $Statistics = $this->model
                ->where($where)
                ->where($where2)
                ->where($where3)
                ->where($where4)
                ->where($where5)
                ->field('sum(total_price) as zsum,sum(freightmj) as freightmj,sum(material) as material,sum(countnum) as countnum')
                ->find();
            $Statistics['zsum'] =  round($Statistics['zsum'],2); //10.46
            $Statistics['zfreightmj'] =  round($Statistics['freightmj'],2);
            $Statistics['zmaterial'] =  round($Statistics['material'],2);
            $Statistics['zcountnum'] =  $Statistics['countnum'];
            $result = array("total" => $list->total(), "rows" => $lists, "Statistics" => $Statistics);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if (!empty($params['material']) && $params['material'] !== $row['material']) {
                        $params['isfiled'] = 1;
                        $params['ismaterial'] = 1;
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 更新每日汇总
     */
    public function addfreight()
    {
        $id = $this->request->param('ids');
        if(!empty($id)){
            //        更新每日汇总
            $Myshopify = new Myshopify();
            $return = $Myshopify->addfreight($id);
            $this->success('更新成功','', $return);
        }else{
            $this->error('参数错误，请重新登录');
        }
    }

    /**
     *
     */
    public function addorderproduct()
    {
        $id = $this->request->param('ids');
        if(!empty($id)){
            $orderquantity = Db::name('fedition_orderquantity')->where('order_id',$id)->select();
            $Myshopify = new Myshopify();
            $special = 0;
            $return = array();
            foreach ($orderquantity as $item) {
                if (!empty($item['product_id'])) {
                    $return = $Myshopify->addorderproduct($item['product_id']);
                } else {
                    $special = 1;
                }
            }
            if ($special == 0) {
                $this->success('更新成功','', $return);
            } else {
                $this->error('部分商品id为空,更新部分成功');
            }
        }else{
            $this->error('参数错误，请重新登录');
        }
    }

    /**
     * 新增采购成本
     */
    public function addmaterial()
    {
        $id = $this->request->param('ids');
        if(!empty($id)){
            //        更新每日汇总
            $Myshopify = new Myshopify();
            $return = $Myshopify->addmaterial($id);
            $this->success('更新成功','', $return);
        }else{
            $this->error('参数错误，请重新登录');
        }
    }

    public function updateordertime()
    {
        $id = $this->request->param('ids');
        $ids_p = $this->request->param('ids_p');
        if (!empty($ids_p)) {
            $id = $ids_p;
        }
        if(!empty($id)){
            //        更新每日汇总
            $Myshopify = new Myshopify();
            $return = $Myshopify->updateordertime($id);
            $this->success('更新成功','', $return);
        }else{
            $this->error('参数错误，请重新登录');
        }
    }

    /**
     * 查看
     */
    public function doubt()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $where2['financial_status'] = array('in','paid,partially_refunded');
            $where2['ismaterial'] = array('in','0,3');

            $list = $this->model
                ->where($where)
                ->where($where2)
                ->order($sort, $order)
                ->paginate($limit);
            $lists = $list->items();
            if($lists){
                foreach ($lists as $k=>$v){
                    $accounturl = Db::name('fedition_accounturl')->where('id', '=', $v['accounturl'])->find();
                    if($accounturl){
                        $lists[$k]['accounturl_name'] = $accounturl['name'];
                    }else{
                        $lists[$k]['accounturl_name'] = '店铺名称已删除';
                    }
                    //运单号
                    $orderfulfillments = Db::name('fedition_orderfulfillments')->where('order_id',$v['id'])->find();
                    if (!empty($orderfulfillments)) {
                        $lists[$k]['tracking_company'] = $orderfulfillments['tracking_company'];
                        $lists[$k]['tracking_number'] = $orderfulfillments['tracking_number'];
                    } else {
                        $lists[$k]['tracking_company'] = '';
                        $lists[$k]['tracking_number'] = '';
                    }
                }
            }
            $result = array("total" => $list->total(), "rows" => $lists);
            return json($result);
        }
        return $this->view->fetch();
    }
}
